package cn.zxyh.service.impl;

import cn.zxyh.mapper.BankCardMapper;
import cn.zxyh.mapper.BillMapper;
import cn.zxyh.pojo.BankCard;
import cn.zxyh.pojo.Bill;
import cn.zxyh.pojo.User;
import cn.zxyh.service.BillService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Bill 账单的Service层
 * By Albert 2020-0525
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BillServiceImpl implements BillService {

    @Resource
    BillMapper billMapper;
    @Resource
    BankCardMapper bankCardMapper;

    /**
     * 添加账单是由外部添加，此处使用虚构的账单
     * @param bill
     */
    @Override
    public void addBill(Bill bill) {

    }

    @Override
    public List<Bill> findBillAll() {
        List<Bill> list = billMapper.findBillAll();
        return list;
    }

    @Override
    public List<Bill> findByUser(User user,int type) {
        if(user == null) return null;
        return billMapper.findByUser(user,type);
    }

    @Override
    public Bill findById(int id) {

        return billMapper.findById(id);
    }

    @Override
    public int payBill(int billId,String password) {
        Bill bill = billMapper.findById(billId);
        if(bill==null){
            return 3;
        }
        int id = bill.getUserId();
        User user = new User();
        user.setId(id);
        List<BankCard> list = bankCardMapper.findAll(user);
        BankCard bankCard = list.get(0);
        if (!password.equals(bankCard.getPassword())) {
            return 2;
        } else if (bill.getMoney() > bankCard.getBalance()) {
            return 1;
        } else {
            bankCardMapper.updateCardBalance(user, bankCard.getBalance() - bill.getMoney());
            billMapper.updateBillStatus(bill.getId());
            return 0;
        }
    }
}
